// 仅执行一次(type)
export default (ujt: any, type: string = 'webserver') => {
    const { $fn, $db, $global } = ujt;
    function userLoginWs() {
        return new Promise((resolve: any, reject: any) => {
            // getOnline()
            //     .then(() => {
            //         if (
            //             $db.channeluser.onlinelist.includes($global.user.info)
            //         ) {
            //             $global.msg.fn({
            //                 type: 'err',
            //                 con: $fn.lg('channeluser.msg.loginerror', [
            //                     $global.user.info.us,
            //                 ]),
            //             });
            //             reject();
            //         } else {
            $fn.ws['web'].wsWatch(
                {
                    ty: 'publish/web',
                },
                (res: any) => {
                    if (res?.db?.exit) {
                        $fn.exit();
                        $fn.sethash(
                            $global.sys?.router?.config?.login || 'user/login'
                        );
                    }
                    if (res?.db?.lang) {
                        if (res.db.langpm) {
                            res.db.con =
                                $fn.lg(
                                    'asai.hostmsg.' + res.db.lang,
                                    res.db.langpm
                                ) || res.db.con;
                        } else {
                            res.db.con =
                                $fn.lg('asai.hostmsg.' + res.db.lang) ||
                                res.db.con;
                        }
                    }
                    if (res?.db === 'pong') {
                        $fn.ws['web'].wsApi('ping').then((resp) => {
                            // console.log(666.007, resp);
                        });
                    } else if (res?.db?.con) {
                        $global.msg.fn(res.db);
                    }
                }
            );
            $fn.ws['web']
                ?.wsApi({
                    ty: 'user/login',
                    db: $global.user.info,
                })
                .then((res: any) => {
                    resolve(res);
                })
                .catch((err: any) => {
                    $global.msg.fn({
                        type: 'err',
                        con: $fn.lg('channeluser.msg.loginerr', [
                            $global.user.info.us,
                        ]),
                    });
                    reject(err);
                });
            // }
            // })
            // .catch((err: any) => {
            //     reject(err);
            // });
        });
    }

    function getOnline() {
        return $fn.ws['web']
            .wsApi({
                ty: 'user/online',
                db: '',
            })
            .then((res: any) => {
                //console.log(666.123, res);
                $db.channeluser.onlinelist = res.db;
            })
            .catch((err: any) => {
                // console.error(666.133, err);
            });
    }
    function initServer() {
        return new Promise<void>((resolve, reject) => {
            try {
                // 判断是否获取到了服务器提供的keycode
                let asaiusercode: any = $fn.As?.localGet('as-user-code');
                if (asaiusercode) {
                    asaiusercode = $fn.As.toObj(asaiusercode);
                    $global.code.pri = asaiusercode[0];
                    $global.code.pub = asaiusercode[1];
                    resolve();
                } else {
                    // 通过API请求，初始化code
                    $fn.api[type]
                        ?.apiGet('/api/init/code/')
                        .then((res: any) => {
                            $global.code.pri = res.data[0];
                            $global.code.pub = res.data[1];
                            $fn.As.localSet(
                                'as-user-code',
                                $fn.As.toStr(res.data)
                            );
                            resolve();
                        })
                        .catch((err: any) => {
                            reject(err);
                        });
                }
            } catch (err: any) {
                reject(err);
            }
        });
    }

    function initToken() {
        if ($global.user.info?.us) {
            $global.code.token =
                $fn.AsCode.asencode($global.user.info?.us, $global.code.pri) +
                '##' +
                $fn.AsCode.asencode($global.user.info?.lv, $global.code.pri) +
                '##' +
                $global.code.pub;
        }
    }

    function initUserToken() {
        return new Promise<void>((resolve, reject) => {
            try {
                initServer()
                    .then(() => {
                        // 判断是否获取到了服务器提供的keycode
                        if (
                            !$global.code.token &&
                            $global.code.pri &&
                            $fn.As.localGet('as-user-info')
                        ) {
                            $global.user.info = $fn.As.toObj(
                                $fn.AsAES.dec($fn.As.localGet('as-user-info'))
                            );
                            initToken();
                        }
                        resolve();
                    })
                    .catch((err: any) => {
                        reject(err);
                    });
            } catch (err: any) {
                reject(err);
            }
        });
    }

    function initUserOnline() {
        return new Promise<void>((resolve, reject) => {
            $global.user.online = 0;
            try {
                initUserToken()
                    .then(() => {
                        // 判断是否获取到了服务器提供的keycode
                        if ($global.code.token) {
                            userLoginWs().then((res: any) => {
                                $global.user.online = 1;
                                resolve();
                            });
                        }
                    })
                    .catch((err: any) => {
                        reject(err);
                    });
            } catch (err: any) {
                reject(err);
            }
        });
    }

    return {
        initServer,
        initUserToken,
        initToken,
        initUserOnline,
        userLoginWs,
        getOnline,
    };
};
